#coding=utf-8
import sys 
import os
import codecs
import getpass
import shutil 
from PyQt4 import QtCore, QtGui, uic 
import pandas as pd,numpy as np 

 
#UI窗口##################################################################################### 
qtCreatorFile ='WM_quick.ui'
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)

#UI窗口初始化##################################################################################### 
class MyApp(QtGui.QMainWindow, Ui_MainWindow):
    global  opdir
    opdir=''
    def __init__( self ): #1级
        QtGui.QMainWindow.__init__( self ) #2级
        Ui_MainWindow.__init__( self ) 
        self.setupUi( self )
        self.textEdit_help.setVisible(False)
        self.pushButton_in.clicked.connect(self.openFile)
        self.pushButton_batch.clicked.connect(self.openFileDirectory)
        self.pushButton_check.clicked.connect(self.check)
        self.pushButton_save.clicked.connect(self.saveFile)
        self.pushButton_help.clicked.connect(self.helpm)
        self.pushButton_reset.clicked.connect(self.reset)
 
    # 显示help文本框###########################################################################
    def helpm(self):
        if self.textEdit_help.isVisible()==False:
            self.textEdit_help.setVisible(True)#3级
        elif self.textEdit_help.isVisible()==True:
            self.textEdit_help.setVisible(False)     
    # 清空使用记录###########################################################################
    def reset(self):
        self.textEdit_help.setVisible(False)
        self.textEdit_path.setText('')
        self.textEdit_show_channel.setText('')
        self.textEdit_show.setText('')
        self.pushButton_command.setEnabled(False)
   # 打开数据文件###########################################################################
    def openFile(self):
        global  opdir
        ##print '\n\n\n\nsingle in $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$'
        if opdir=='':
            fileName = QtGui.QFileDialog.getOpenFileName(self,'Open file', 'C:/Users/'+getpass.getuser()+'/Desktop/',"xls Files (*.xls);;Files (*)")
        else :
            fileName = QtGui.QFileDialog.getOpenFileName(self,'Open file', opdir,"xls Files (*.xls);;Files (*)")
        ni=unicode(QtCore.QString(fileName).toUtf8(), 'utf-8', 'ignore')            
        opdir=os.path.abspath(ni)
        if ni!='':
            self.textEdit_show.append('++Single File in++++++++++++++++++++++++++++++++++')
            self.textEdit_path.setText(ni)  
            self.textEdit_show.append(ni+'  file in!')
            self.pushButton_check.setEnabled(True)
            self.pushButton_check.setText('single check')

    def openFileDirectory(self):
        global  opdir
        if opdir=='':
            fileName = QtGui.QFileDialog.getExistingDirectory(self,'选取文件夹', 'C:/Users/'+getpass.getuser()+'/Desktop/',os.path.abspath('.'))
        else :
            fileName = QtGui.QFileDialog.getExistingDirectory(self,'选取文件夹', opdir,os.path.abspath('.'))
        ni=unicode(QtCore.QString(fileName).toUtf8(), 'utf-8', 'ignore')            
        opdir=os.path.abspath(ni)
        if ni!='':
            self.textEdit_show.append('++Batch in++++++++++++++++++++++++++++++++++')
            self.textEdit_path.setText(ni)  
            self.textEdit_show.append(ni+'  file in!')
            self.pushButton_check.setEnabled(True)
            self.pushButton_check.setText('batch check')
##
##
##
##        
##        fileName = QtGui.QFileDialog.getExistingDirectory(self,"选取文件夹",os.path.abspath('.'))
##        ni=str(fileName)
##        self.textEdit_path.setText(ni)  
##        self.textEdit_show.append(ni+'  FileDirectory in!')
##        print self.textEdit_path.toPlainText()    

            
   # 保存check结果###########################################################################
    def saveFile(self,tempd):
        source=unicode(QtCore.QString(self.textEdit_path.toPlainText()).toUtf8(), 'utf-8', 'ignore')
        import datetime 
        today = datetime.date.today() 
        source=source.replace(source.split('/')[-1],'./'+u'数据核对表'+today.strftime("%Y %m %d") +'----'+source.split('/')[-1])
        fileName = QtGui.QFileDialog.getSaveFileName(self,'Save file', source,"xls Files (*.xls);;Files (*)")
        fileName=unicode(QtCore.QString(fileName).toUtf8(), 'utf-8', 'ignore')
        f2=codecs.open(fileName,'w','utf-16')
        f2.write(codecs.open("temp_.xls",'r','utf-16').read())  
        f2.close()

        
    def check(self):
        if self.pushButton_check.text()=='single check':
            self.check_single()
        elif self.pushButton_check.text()=='batch check':
            self.check_batch()

        
   # 检查日清项###########################################################################
    def check_single(self):
        shop = {u'C007101310':u'1013-西黄村店', u'C007101410':u'1014-八角北里店',u'C007101610':u'1016-昌平店',u'C007101910':u'1019-科大店',
                u'C007126410':u'1264-万源店',u'C007127910':u'1279-通州梨园店',u'C007129210':u'1292-新华联家园店',u'C007131210':u'1312-开阳桥店',
                u'C007136410':u'1364-北沙滩店',u'C007138910':u'1389-北七家店',u'C007142010':u'1420-西黄村二店',u'C007144010':u'1440-金顶阳光店'}
        ###读入数据文件
        FileName=unicode(QtCore.QString(self.textEdit_path.toPlainText()).toUtf8(), 'utf-8', 'ignore')
        ###wm数据文件为utf-16仿xls格式 split=('	')
        f = codecs.open(FileName,'r','utf-16').read()
        inutf8=f.encode("utf-8")
        datachecked=''
        pp=''
        head=''
        calc=''
        data=inutf8.split('\n')
        ###1商行信用卡2交通信用卡3浦发信用卡4邮储6翼支付7手机红包8一卡通9美通卡11养老卡
        i=0
        date=''
        ###print inutf8
        stlist= self.check_st(inutf8)
        st=stlist[4]
        dateloc=stlist[2]
        amtloc=stlist[3]
        typei=stlist[6]
        #datachecked+=stlist[5]+'\n'
        #datachecked+=data[st-2].rstrip()+'	差异金额\n'
        i=0
        date=''
        dataout=''
        for x in data:
            if '	*	' in x:
                se=i-1#4级
                monthsum=x.split('	')
                # eval(monthsum[amtloc].replace(',',''))#月度差异
                if abs(eval(monthsum[amtloc].replace(',','')))-0<=0.0001 :
                    datachecked+=x+'\n'
                    monthsumcalc=0
                    datap=''
                    date=''
                    daysum=0
                    whk=0
                    monthsumcalc=0
                else :                    
                    monthsumcalc=0
                    datap=''
                    date=''
                    daysum=0
                    whk=0
                    monthsumcalc=0
                    sst=st
                    sse=st
                    for xx in data[st:se+1]:
                        cc=xx.split('	')#6级
                        money=eval(cc[amtloc].replace(',',''))
                        if (xx==data[se]) and (date!=cc[dateloc]):
                            if abs(daysum)!=0:
                                datachecked+=self.check_findsame(datap,stlist).rstrip()+' 	'+str(daysum).strip()+'\n'
                                monthsumcalc+=daysum
                            if money!=0 :
                                datachecked+=data[se].rstrip()+'	'+str(money).rstrip()+'\n'
                                monthsumcalc+=money
                            datap=''
                            daysum=money
                            if cc[typei]=='BR':
                                whk=money
                        elif (xx==data[se]) and (date==cc[dateloc]):
                            daysum=daysum+money
                            if abs(daysum)!=0:
                                datap+=xx+'\n'
                                datachecked+=self.check_findsame(datap,stlist).rstrip()+' 	'+str(daysum).strip()+'\n'
                                monthsumcalc+=daysum
                            datap=''
                            daysum=money
                            for iwhk in range(se-st):
                                if cc[typei]=='BR' and data[se-iwhk-1]=='BR':
                                    c2=data[se-iwhk].split('	')   
                                    whk+= eval(c2[amtloc].replace(',',''))
                                else:
                                    break
                        elif (xx!=data[se]) and(date == cc[dateloc] ):
                            daysum=daysum+money
                        elif (xx!=data[se]) and(date != cc[dateloc]):
                            ##print date,cc[dateloc]
                            if abs(daysum)!=0:
                                datachecked+=self.check_findsame(datap,stlist).rstrip()+' 	'+str(daysum).strip()+'\n'
                                monthsumcalc+=daysum
                            datap=''
                            daysum=money    
                        date=cc[dateloc]
                        datap+=xx+'\n'
                        
                    if abs(monthsumcalc-eval(monthsum[amtloc].replace(',','')))<=0.0001:
                        datachecked+=x.strip()+'	calc_cok  '+str(monthsumcalc)+'\n'
                        calc='calc_cok'
                    else :
                        datachecked+=x.strip()+'	calc_error  '+str(monthsumcalc)+'\n'
                        calc='calc_error'
                st=i+1
                shopkey=(monthsum[amtloc+1]).rstrip()
                shopkey=shop[shopkey]
                head=shopkey+u'--数据核对表'+'\n' +u'科目号	科目名称	截止月底余额	其中:未回款	差异	累计多刷	错报差异	当月差异	原因分析	财务人员'+'\n'
       
                
                ye=eval((monthsum[amtloc]).replace(',','').rstrip())
                pp=str(stlist[0])+'	'+stlist[1].rstrip()+'	'+str(ye)+'	'+str(whk)+'	'+str(ye-whk)+'\n'
                datachecked=head.encode('UTF-8')+pp+str(datachecked)
                dataout+=datachecked
                datachecked=''
            i+=1            

        dataout= dataout.replace(' ','')        
        okout=str(dataout).decode("utf-8")
        self.textEdit_show.setText(okout)
        self.textEdit_show.append('\n calc result++++++++++++'+calc)
        #print okout
        f2= codecs.open("temp_.xls",'w','utf-16')
        f2.write(okout)
        f2.close()
        #self.check_toxls(datachecked,stlist)

    def check_batch(self):
        print 'batch'
        
   # 检查数据文件开始位置###########################################################################            
    def check_st(self,din):
        din=din.replace('\\','')
        num=din.split('\n')
        itemnum='--'
        itemname='--'
        temp='应收账款'
        amtloc=0
        dateloc=0
        for x in num:
            if '总帐科目' in x:
                itemst=x
                datas=x.split('		')
                i=0
                for xx in datas:                   
                    if '应收账款'  in xx:
                        itemname=xx
                    elif xx.isdigit():
                        itemnum=xx
                    i+=1

            if '本币金额' in x:
                datast=num.index( x )+2
                datas=x.split('	')
                i=0
                for xx in datas:
                    if '过帐日期' in xx:
                        dateloc=i
                    elif '本币金额' in xx:
                        amtloc=i
                    elif '类型' in xx:
                        typei=i
                    i+=1 
        st=[itemnum,itemname,dateloc,amtloc,datast,itemst,typei]
        return st
    
   # 检查日0项###########################################################################                                      
    def check_findsame(self,datap,stlist):
        st=stlist[4]
        dateloc=stlist[2]
        amtloc=stlist[3]
        datao=datap
        num=datap.split('\n')
        for x in num:
            if x!='':
                datas=x.split('	')
                data=datas[amtloc]
                if '-' in data:
                    for xx in num:
                        if xx!='':
                            d1=data.replace('-','')
                            d1=d1.replace(',','')
                            d2=xx.split('	')[amtloc]
                            d2=d2.replace(',','')
                            if abs(eval(d1)-eval(d2))<=0.0001:
                                datao=datao.replace(xx+'\n','')
                                datao=datao.replace(x+'\n','')
                elif '-' not in data:
                    for xx in num:
                        if xx!='':
                            d1='-'+data
                            d1=d1.replace(',','')
                            d2=xx.split('	')[amtloc]
                            d2=d2.replace(',','')
                            if abs(eval(d1)-eval(d2))<=0.0001:
                                datao=datao.replace(xx+'\n','')
                                datao=datao.replace(x+'\n','')
        return datao
    
if __name__ == "__main__" :
    app = QtGui.QApplication(sys.argv)
    window = MyApp()
    window.show()
    sys.exit(app.exec_()) 
